package cn.christ.com.mobilesafe.common;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * Created by Administrator on 2018/7/14.
 * 封装公共类，屏幕的宽高获取，单位转换，主线程运行等
 */

public class Global {
    public static Context context;
    //屏幕密度
    public static float density;
    //屏幕宽度
    public static float screenWidth;
    //屏幕高度
    public static float screenHeight;

    public static void init(Context context) {
        Global.context = context;
        initScreenSize();
    }

    /**
     * 初始化屏幕的宽高
     */
    private static void initScreenSize() {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        density = dm.density;
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;
    }

    /**
     * dp转化为px
     *
     * @param dp
     * @return
     */
    public static int dp2px(int dp) {
        return (int) (dp * density + 0.5f);
    }

    /**
     * 填充布局
     *
     * @param layoutResID 资源文件
     * @param parent      子控件挂在到父控件
     * @return
     */
    public static View inflate(int layoutResID, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(layoutResID, parent, false);
    }

    /**
     * 填充个布局，没有父控件
     *
     * @param layoutResID 资源文件
     * @return
     */
    public static View inflate(int layoutResID) {
        return inflate(layoutResID, null);
    }

    /**
     * 获取到主线程的handler
     */
    private static Handler handler = new Handler(Looper.getMainLooper());

    /**
     * 判断当前线程是否是主线程
     *
     * @return
     */
    public static boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

    /**
     * 在主线程中运行
     *
     * @param run
     */
    public static void runOnMainThread(Runnable run) {
        if (isMainThread()) {
            run.run();
        } else {
            handler.post(run);
        }
    }

    private static Toast toast;

    /**
     * 在主线程中弹toast
     */
    public static void showToast(final String msg) {
        runOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (toast == null) {
                    toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                }
                toast.setText(msg);
                toast.show();
            }
        });
    }

    /**
     * 获取资源id
     * @return
     */
    public static String getResourcesString(int id) {
        return context.getResources().getString(id);
    }

    /**
     * 跳转activity
     *
     * @param clazz
     */
    public static void startActivity(Activity context,Class clazz) {
        Intent intent = new Intent(context, clazz);
        context.startActivity(intent);
        context.finish();
    }

    /**
     * 跳转activity,不finish
     *
     * @param clazz
     */
    public static void startActivityNotFinish(Activity context,Class clazz) {
        Intent intent = new Intent(context, clazz);
        context.startActivity(intent);
    }


    //=============沉侵式==(end)====================================================================
    public static View statusBarView;

    /**
     * 设置全屏沉浸式效果
     * 调用此方法，界面内容可以延伸显示到状态栏上，4.4状态栏为半透明色，5.0以上状态栏会变成透明色
     */
    public static void setNoStatusBarFullMode(Activity activity) {
        //sdk 4.4 全屏设置，状态栏半透明
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow(); //获取到窗口
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //设置半透明
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); //设置半透明
            if (statusBarView != null) { //如果状态栏有高度，移除状态栏的view
                ViewGroup root = (ViewGroup) activity.findViewById(android.R.id.content);
                root.removeView(statusBarView);
            }
            return;
        }

        //sdk 5.x 比较简单，状态栏直接设置透明色，底部虚拟键盘设置半透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//半透明，虚拟按键
            window.setStatusBarColor(Color.TRANSPARENT); //全透明
            return;
        }
    }

    /**
     * 设置控件的paddingTop,使它不被StatusBar覆盖
     *
     * @param view
     */
    public static void setStatusBarPadding(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int marginTop = getStatusBarHeight(view.getContext());
            view.setPadding(view.getPaddingLeft(), marginTop,
                    view.getPaddingRight(), view.getPaddingBottom());
            return;
        }
    }

    /**
     * 通过反射的方式获取状态栏高度，
     * 一般为24dp,有些可能特殊，所以需要反射动态获取
     */
    private static int getStatusBarHeight(Context context) {
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object obj = clazz.newInstance();
            Field field = clazz.getField("status_bar_height");
            int id = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(id);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("statusBarHeightError", "-------无法获取到状态栏高度");
        }
        return dp2px(24);
    }

    /**
     * 设置状态栏的颜色
     *
     * @param activity
     * @param statusColor
     */
    private static void setStatusBarColor(Activity activity, int statusColor) {
        //sdk4.4
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                ViewGroup root = (ViewGroup) activity.findViewById(android.R.id.content);
                if (statusBarView == null) {
                    statusBarView = new View(activity);
                    statusBarView.setBackgroundColor(statusColor);
                } else {
                    //先解除父控件关系，否则重复把一个控件多次
                    //添加到其他父控件中会出错
                    ViewParent parent = statusBarView.getParent();
                    if (parent != null) {
                        ViewGroup viewGroup = (ViewGroup) parent;
                        if (viewGroup != null) {
                            viewGroup.removeView(statusBarView);
                        }
                    }
                    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
                    root.addView(statusBarView, params);
                }
                return;
            }
        }

        //sdk 5.x
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setStatusBarColor(statusColor);
            return;
        }
    }

    //=============虚拟按键(导航栏的适配)==========================================================

    /**
     * 往下移动控件，移动的距离为状态栏高度
     */
    public static void moveViewDown(View view) {
        //sdk4.4:kitkat
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //状态栏高度
            int distannce = Global.getStatusBarHeight(view.getContext());
            ViewParent parent = view.getParent();
            if (parent instanceof LinearLayout) {
                //通过marginTop属性让控件往下偏移一段距离
                //相当于:android:layout_marginTop="24dp"
                ((LinearLayout.LayoutParams) view.getLayoutParams()).topMargin = distannce;
            } else if (parent instanceof RelativeLayout) {
                ((RelativeLayout.LayoutParams) view.getLayoutParams()).topMargin = distannce;
            } else if (parent instanceof FrameLayout) {
                ((FrameLayout.LayoutParams) view.getLayoutParams()).topMargin = distannce;
            }
            return;
        }
    }

    /**
     * 往上移动Activity中所有的控件，移动的距离为系统导航栏的高度
     *
     * @param activity
     */
    public static void moveViewUp(Activity activity) {
        if (!Global.checkDeviceHasNavigationBar(activity)) {
            return;
        }

        //4.4以上，并且，有虚拟按键的情况下，才调用设置paddingBottom
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ViewGroup root = (ViewGroup) activity.findViewById(android.R.id.content);
            root.setBackgroundColor(Color.BLACK);
            root.setPadding(root.getTop(), root.getLeft(), root.getRight(), Global.getNavigationBarHeight(activity));
        }
    }

    /**
     * 获取系统导航栏的高度(虚拟按键)
     *
     * @param activity
     * @return
     */
    private static int getNavigationBarHeight(Activity activity) {
        Resources resources = activity.getResources();
        int id = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        //获取NavigationBar的高度
        int height = resources.getDimensionPixelSize(id);
        return height;
    }

    /**
     * 获取是否存在NavigationBar(虚拟按键)
     *
     * @param activity
     * @return
     */
    private static boolean checkDeviceHasNavigationBar(Activity activity) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }

        //机型适配:华为
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("l".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hasNavigationBar;
    }

    //=============沉侵式==(end)====================================================================

}
